package pe.gob.minam.sismon.web.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import pe.gob.minam.sismon.core.util.MessageException;

public final class UtilWeb {

	@Autowired
	private static final Logger LOGGER = Logger.getLogger(UtilWeb.class);

	private UtilWeb() {

	}

	public static Object getObjetoSesion(String objectName) {
		HttpServletRequest request = (HttpServletRequest) getInstancia()
				.getExternalContext().getRequest();
		return request.getSession(false).getAttribute(objectName);
	}

	private static FacesContext getInstancia() {
		return FacesContext.getCurrentInstance();
	}

	public static HttpSession getSesion() {
		return (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
	}

	public static void sendRedirect(String ruta) {
		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		try {
			FacesContext.getCurrentInstance().responseComplete();
			response.sendRedirect(FacesContext.getCurrentInstance()
					.getExternalContext().getRequestContextPath()
					+ "/faces/" + ruta);
		} catch (IOException e) {
			String[] errores = MessageException.getMessageExceptionPrintAop(e,
					e.getMessage());
			LOGGER.error(errores[1]);
		}
	}

	public static void irIniciarSesion() {
		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		try {
			FacesContext.getCurrentInstance().responseComplete();
			response.sendRedirect(FacesContext.getCurrentInstance()
					.getExternalContext().getRequestContextPath());
		} catch (IOException e) {
			String[] errores = MessageException.getMessageExceptionPrintAop(e,
					e.getMessage());
			LOGGER.error(errores[1]);
		}
	}

	public static void setObjetoSesion(String objectName, Object object) {
		LOGGER.info("SE PUSO EN SESION EL OBJETO " + objectName + " DEL TIPO "
				+ object.getClass());
		HttpServletRequest request = (HttpServletRequest) getInstancia()
				.getExternalContext().getRequest();
		request.getSession(false).setAttribute(objectName, object);
	}

	public static void removeObjetoSesion(String objectName) {
		LOGGER.info("SE QUITO DE SESION EL OBJETO " + objectName);
		HttpServletRequest request = (HttpServletRequest) getInstancia()
				.getExternalContext().getRequest();
		request.getSession(false).removeAttribute(objectName);
	}

	public static String obtenerFechaActual(String formato) {
		Date ahora = new Date();
		SimpleDateFormat formateador = new SimpleDateFormat(formato);
		return formateador.format(ahora);
	}

	public static String formatearFecha(String formato, Date fecha) {
		SimpleDateFormat formateador = new SimpleDateFormat(formato);
		return formateador.format(fecha);
	}

	public static String darFormatoDosDecimales(Object obj) {
		NumberFormat numberFormat = NumberFormat.getInstance();
		numberFormat.setGroupingUsed(false);
		numberFormat.setMaximumFractionDigits(ConstantesWeb.N2);
		numberFormat.setRoundingMode(RoundingMode.DOWN);
		numberFormat.setMinimumFractionDigits(ConstantesWeb.N2);

		return numberFormat.format(obj);
	}

	public static BigDecimal darFormatoBigDecimal(BigDecimal numero) {
		return numero.round(new MathContext(numero.precision() - numero.scale()
				+ ConstantesWeb.N2, RoundingMode.HALF_UP));
	}

	public static void mensajeError(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, mensaje, ""));
	}

	public static void mensajeInformacion(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, mensaje, ""));
	}

	public static void mensajeAdvertencia(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_WARN, mensaje, ""));
	}
	
	public static void mensajeFatal(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_FATAL, mensaje, ""));
	}

	public static String obtenerDescDia(BigInteger dia) {
		Calendar c = Calendar.getInstance();
		c.clear();
		c.get(Calendar.DAY_OF_WEEK);
		c.add(Calendar.DAY_OF_WEEK, dia.intValue() + ConstantesWeb.N3);
		c.get(Calendar.DAY_OF_WEEK);
		return formatearFecha("EEEE", c.getTime());
	}

	public static void mostrarMensajeFatal(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage(FacesMessage.SEVERITY_FATAL,
						ConstantesWeb.OCURRIO_ERROR, mensaje));
	}

	public static boolean esNumericoDecimal(String cadena) {
		boolean retorno;
		try {
			if (cadena == null) {
				retorno = false;
			} else {
				String cadenaNumero = cadena.replaceAll(",", ".");
				Double.parseDouble(cadenaNumero.trim());
				retorno = true;
			}
		} catch (NumberFormatException nfe) {
			retorno = false;
		}
		return retorno;
	}
	
	public static String getContextParam(String nameParam){
		String valor = "";
		try {
			FacesContext ctx = FacesContext.getCurrentInstance();
			valor = ctx.getExternalContext().getInitParameter(nameParam);
		} catch(Exception e){			
		}		
		return valor;
	}
	
}
